'use client';

import { useState, useEffect } from 'react';
import TokenList from '@/components/TokenList';
import PositionsList from '@/components/PositionsList';
import TradeHistory from '@/components/TradeHistory';
import { useWebSocket } from '@/components/WebSocketProvider';

export default function Home() {
  const [activeTab, setActiveTab] = useState('tokens');
  const [positions, setPositions] = useState([]);
  const [trades, setTrades] = useState([]);
  const { tokens } = useWebSocket();

  // 获取持仓信息
  const fetchPositions = async () => {
    try {
      const response = await fetch('/api/positions');
      const data = await response.json();
      setPositions(data);
    } catch (error) {
      console.error('获取持仓信息失败:', error);
    }
  };

  // 获取交易历史
  const fetchTrades = async () => {
    try {
      const response = await fetch('/api/trades');
      const data = await response.json();
      setTrades(data);
    } catch (error) {
      console.error('获取交易历史失败:', error);
    }
  };

  useEffect(() => {
    fetchPositions();
    fetchTrades();

    // 每10秒刷新持仓和交易历史数据
    const interval = setInterval(() => {
      if (activeTab === 'positions') {
        fetchPositions();
      } else if (activeTab === 'trades') {
        fetchTrades();
      }
    }, 10000);

    return () => clearInterval(interval);
  }, [activeTab]);

  const tabs = [
    { id: 'tokens', name: '代币监控', count: tokens.length },
    { id: 'positions', name: '持仓管理', count: positions.length },
    { id: 'trades', name: '交易历史', count: trades.length }
  ];

  return (
    <div className="space-y-6">
      {/* 标签页导航 */}
      <div className="border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === tab.id
                  ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
              }`}
            >
              {tab.name}
              {tab.count !== null && (
                <span className="ml-2 bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-gray-100 py-0.5 px-2.5 rounded-full text-xs">
                  {tab.count}
                </span>
              )}
            </button>
          ))}
        </nav>
      </div>

      {/* 标签页内容 */}
      <div className="mt-6">
        {activeTab === 'tokens' && (
          <TokenList />
        )}
        
        {activeTab === 'positions' && (
          <PositionsList positions={positions} onRefresh={fetchPositions} />
        )}
        
        {activeTab === 'trades' && (
          <TradeHistory trades={trades} onRefresh={fetchTrades} />
        )}
      </div>
    </div>
  );
}
